﻿using System;
using System.Collections.Generic;
using System.Text;
using SharpCommunications.Logging;

namespace SharpCommunications.TestServer
{
    public class ConnectionThreads : IDisposable
    {
        public List<ConnectionThread> Threads { get; set; }
        public ConnectionThreadTerminatedHandlerDelegate ConnectionThreadTerminatedHandler_Delegate;

        public ConnectionThreads()
        {
            this.ConnectionThreadTerminatedHandler_Delegate = new ConnectionThreadTerminatedHandlerDelegate(ConnectionThreadTerminatedHandler);
            this.Threads = new List<ConnectionThread>();
        }

        public void Add(ConnectionThread connectionThread)
        {
            this.Threads.Add(connectionThread);
        }

        protected void ConnectionThreadTerminatedHandler(ConnectionThread connectionThread)
        {
            this.Threads.Remove(connectionThread);
        }

        #region IDisposable Members

        public void Dispose()
        {
            Location location = new Location("ConnectionThreads.Dispose()");

            foreach (ConnectionThread connectionThread in Threads)
            {
                try
                {
                    connectionThread.Dispose();
                }
                catch (Exception ex)
                {
                    LogFactory.Log.ErrorMessage(location, ex, true);
                }
            }
        }

        #endregion
    }
}
